/*    
 * 五星电器公司拥有完全的版权   
 * 使用者必须经过许可
 *----------------------------------------------------------------------*
 * Copyright  (c) 2016 FiveStar Co.,Ltd. All rights reserved
 * Author       : FiveStar Development
 * Description  : Cache.java
 *----------------------------------------------------------------------*
 * Change-History: Change history
 * Developer  Date      Description
 * shidong  2017年7月3日 Short description containing Message, Note ID or CR ID
 *----------------------------------------------------------------------*  
 */
package com.twp.auth.utils;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 内存cache
 *
 * @since JDK 1.8
 */
@Component
public class Cache {
    private static ConcurrentHashMap<String, CacheBean<Object>> cacheMap = new ConcurrentHashMap<String, CacheBean<Object>>();

    /**
     * 缓存超时时间
     */
    private final static long MEM_CACHE_OVERTIME = 12 * 60 * 60 * 1000L;

    @Resource
    HazelcastInstance hazelcastInstance;

    public <T> T getByHazelcast(String key) {
        IMap<String, T> cacheMap_ = hazelcastInstance.getMap(key);
        if (cacheMap_ ==null || !cacheMap_.containsKey(key)) {
            return null;
        }
        return cacheMap_.get(key);
    }

    public <T> void putByHazelcast(String key, T o) {
        IMap<String, T> cacheMap_ = hazelcastInstance.getMap(key);
        cacheMap_.put(key, o);
    }

    public void clearByHazelcast(String key){
        IMap<String, Object> cacheMap_ = hazelcastInstance.getMap(key);
        cacheMap_.remove(key);
    }

    public static Object get(String key) {
        if (!cacheMap.containsKey(key)) {
            return null;
        }

        CacheBean<Object> cacheBean = cacheMap.get(key);
        if (System.currentTimeMillis() - cacheBean.getTime() > MEM_CACHE_OVERTIME) {
            //超时
            cacheMap.remove(key);
            return null;
        }

        return cacheBean.getT();
    }

    public static void put(String k, Object o) {
        CacheBean<Object> cacheBean = new CacheBean<Object>(o);
        cacheMap.put(k, cacheBean);
    }

    public static void clear(String k) {
        cacheMap.remove(k);
    }

    public static void clearAll() {
        cacheMap.clear();
    }

    @NoArgsConstructor@AllArgsConstructor@Data
    private static class CacheBean<T> implements java.io.Serializable {
        private T t;
        private long time;

        public CacheBean(T t) {
            this.t = t;
            this.time = System.currentTimeMillis();
        }
    }
}
